package com.msxt.utils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import cn.hutool.core.bean.BeanUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

/**
 * Mybatis-Plus工具类
 */
public class MPUtil {
	public static final char UNDERLINE = '_';

	//mybatis plus allEQ 表达式转换
	public static Map<String, Object> allEQMapPre(Object bean, String pre) {
		Map<String, Object> map = BeanUtil.beanToMap(bean);
		return camelToUnderlineMap(map, pre);
	}

	//mybatis plus allEQ 表达式转换
	public static Map<String, Object> allEQMap(Object bean) {
		Map<String, Object> map = BeanUtil.beanToMap(bean);
		return camelToUnderlineMap(map, "");
	}

	public static <T> QueryWrapper<T> allLikePre(QueryWrapper<T> wrapper, Object bean, String pre) {
		Map<String, Object> map = BeanUtil.beanToMap(bean);
		Map<String, Object> result = camelToUnderlineMap(map, pre);
		return genLike(wrapper, result);
	}

	public static <T> QueryWrapper<T> allLike(QueryWrapper<T> wrapper, Object bean) {
		Map<String, Object> result = BeanUtil.beanToMap(bean, true, true);
		return genLike(wrapper, result);
	}

	public static <T> QueryWrapper<T> genLike(QueryWrapper<T> wrapper, Map<String, Object> param) {
		Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = it.next();
			String key = entry.getKey();
			String value = (String) entry.getValue();
			wrapper.like(key, value);
		}
		return wrapper;
	}

	/**
	 * 根据实体对象属性构建查询条件
	 * @param wrapper 查询包装器
	 * @param object 实体对象
	 * @return 构建后的查询包装器
	 */
	public static <T> QueryWrapper<T> likeOrEq(QueryWrapper<T> wrapper, Object object) {
		if (object == null) {
			return wrapper;
		}

		try {
			// 使用反射获取对象属性
			Field[] fields = object.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				Object value = field.get(object);
				if (value != null) {
					String fieldName = field.getName();
					// 排除特殊字段
					if ("serialVersionUID".equals(fieldName) || "page".equals(fieldName) ||
							"limit".equals(fieldName) || "order".equals(fieldName)) {
						continue;
					}

					// 处理字符串类型的LIKE查询
					if (value instanceof String && StringUtils.isNotBlank((String) value)) {
						wrapper.like(fieldName, value);
					}
					// 处理其他类型的等值查询
					else {
						wrapper.eq(fieldName, value);
					}
				}
			}
		} catch (IllegalAccessException e) {
			throw new Error("反射获取对象属性异常！");
		}
		return wrapper;
	}

	public static <T> QueryWrapper<T> genLikeOrEq(QueryWrapper<T> wrapper, Map<String, Object> param) {
		Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = it.next();
			String key = entry.getKey();
			if (entry.getValue().toString().contains("%")) {
				wrapper.like(key, entry.getValue().toString().replace("%", ""));
			} else {
				wrapper.eq(key, entry.getValue());
			}
		}
		return wrapper;
	}

	public static <T> QueryWrapper<T> allEq(QueryWrapper<T> wrapper, Object bean) {
		Map<String, Object> result = BeanUtil.beanToMap(bean, true, true);
		return genEq(wrapper, result);
	}

	public static <T> QueryWrapper<T> genEq(QueryWrapper<T> wrapper, Map<String, Object> param) {
		Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = it.next();
			String key = entry.getKey();
			wrapper.eq(key, entry.getValue());
		}
		return wrapper;
	}

	public static <T> QueryWrapper<T> between(QueryWrapper<T> wrapper, Map<String, Object> params) {
		for (String key : params.keySet()) {
			String columnName = "";
			if (key.endsWith("_start")) {
				columnName = key.substring(0, key.indexOf("_start"));
				if (StringUtils.isNotBlank(params.get(key).toString())) {
					wrapper.ge(columnName, params.get(key));
				}
			}
			if (key.endsWith("_end")) {
				columnName = key.substring(0, key.indexOf("_end"));
				if (StringUtils.isNotBlank(params.get(key).toString())) {
					wrapper.le(columnName, params.get(key));
				}
			}
		}
		return wrapper;
	}

	public static <T> QueryWrapper<T> sort(QueryWrapper<T> wrapper, Map<String, Object> params) {
		String order = "";
		if (params.get("order") != null && StringUtils.isNotBlank(params.get("order").toString())) {
			order = params.get("order").toString();
		}
		if (params.get("sort") != null && StringUtils.isNotBlank(params.get("sort").toString())) {
			if (order.equalsIgnoreCase("desc")) {
				wrapper.orderByDesc(params.get("sort").toString());
			} else {
				wrapper.orderByAsc(params.get("sort").toString());
			}
		}
		return wrapper;
	}

	/**
	 * 驼峰格式字符串转换为下划线格式字符串
	 */
	public static String camelToUnderline(String param) {
		if (param == null || "".equals(param.trim())) {
			return "";
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append(UNDERLINE);
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	public static Map<String, Object> camelToUnderlineMap(Map<String, Object> param, String pre) {
		Map<String, Object> newMap = new HashMap<>();
		Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = it.next();
			String key = entry.getKey();
			String newKey = camelToUnderline(key);
			if (pre.endsWith(".")) {
				newMap.put(pre + newKey, entry.getValue());
			} else if (StringUtils.isEmpty(pre)) {
				newMap.put(newKey, entry.getValue());
			} else {
				newMap.put(pre + "." + newKey, entry.getValue());
			}
		}
		return newMap;
	}
}